<template>
  <div class="common-layout">
    <el-container>
      <el-header></el-header>
      <el-main>
        <div class="center-wrapper">
          <div class="logo__bg">
            <el-image style="width: 100%; height: 100%; border-radius:10px 0 0 10px;" :src='bgLeftSrc' fit="cover"
              :preview-src-list='bgLeftAmplify' />
          </div>
          <el-card shadow='never' style="width: 50%;height: 100%; border-radius:0 10px 10px 0;">
            <div class="loginPage">
              <el-tabs :stretch="true" v-model="activeName">
                <!-- 登录表单 -->
                <el-tab-pane label="登录" name="login">
                  <el-form class="loginForm" :model="loginForm" ref="loginFormRef" :rules="loginRules" status-icon>
                    <el-form-item prop="account">
                      <!-- 登录表单账号输入 -->
                      <el-input v-model="loginForm.account" placeholder="请输入数字账号">
                        <template #prepend><el-icon>
                            <User />
                          </el-icon></template>
                      </el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                      <el-input v-model="loginForm.password" placeholder="请输入密码" show-password
                        @keyup.enter="handleLogin">
                        <template #prepend><el-icon>
                            <Lock />
                          </el-icon></template>
                      </el-input>
                    </el-form-item>
                    <div class="login-options">
                      <div><el-checkbox v-model="rememberLogin" label="记住密码" size="large" /></div>
                      <!-- 恢复忘记密码链接 -->
                      <div class="forgot-password" @click="openForget">忘记密码</div>
                    </div>
                    <el-button class="login-button" type="primary" @click="handleLogin"
                      :loading="loginLoading">登录</el-button>
                    <div class="register-prompt">
                      还没有账号?<span class="register-link" @click="switchToRegister">马上注册</span>
                    </div>
                  </el-form>
                </el-tab-pane>

                <!-- 注册表单 -->
                <el-tab-pane label="注册" name="register">
                  <el-form class="loginForm" :model="registerForm" ref="registerFormRef" :rules="registerRules"
                    status-icon>
                    <el-form-item prop="account">
                      <!-- 注册表单账号输入 -->
                      <el-input v-model="registerForm.account" placeholder="请输入数字账号">
                        <template #prepend><el-icon>
                            <User />
                          </el-icon></template>
                      </el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                      <el-input v-model="registerForm.password" placeholder="请输入密码" show-password
                        @keyup.enter="handleRegister">
                        <template #prepend><el-icon>
                            <Lock />
                          </el-icon></template>
                      </el-input>
                    </el-form-item>
                    <el-form-item prop="rpassword">
                      <el-input v-model="registerForm.rpassword" placeholder="请再次输入密码" show-password
                        @keyup.enter="handleRegister">
                        <template #prepend><el-icon>
                            <Lock />
                          </el-icon></template>
                      </el-input>
                    </el-form-item>
                    <el-button class="register-button" type="primary" @click="handleRegister"
                      :loading="registerLoading">注册</el-button>
                    <div class="login-prompt">
                      已有账号?<span class="login-link" @click="switchToLogin">立即登录</span>
                    </div>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-card>
        </div>
      </el-main>
      <el-footer class="footer-wrapper">
        <div class="footer-content">
          <span v-for="(item, index) in footerItems" :key="index">
            {{ item }} <span v-if="index < footerItems.length - 1">&emsp;|&emsp;</span>
          </span>
        </div>
      </el-footer>
    </el-container>
  </div>

  <!-- 忘记密码组件 - 添加v-model控制显示 -->
  <ForgetPassword v-model:visible="showForgetPassword" @resetSuccess="handleResetSuccess" />
</template>

<style lang="scss" scoped>
/* 保持原有样式不变 */
body {
  background: url('@/views/login/images/login_bg.png') center/cover no-repeat fixed;
  margin: 0;
  height: 100vh;
}

.common-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.center-wrapper {
  margin: 15vh auto;
  width: 80vh;
  height: 50vh;
  display: flex;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  .logo__bg {
    width: 50%;
    height: 100%;
  }

  .loginPage {
    width: 85%;
    padding: 2rem;
    margin-top: 2rem;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .loginForm {
      .login-options {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;

        .forgot-password {
          cursor: pointer;
          font-size: 14px;
          color: #409eff;
          line-height: 40px;
          transition: color 0.3s;

          &:hover {
            color: #66b1ff;
            text-decoration: underline;
          }
        }
      }

      .register-prompt,
      .login-prompt {
        margin-top: 15px;
        font-size: 14px;
        text-align: center;
        color: #606266;

        .register-link,
        .login-link {
          cursor: pointer;
          color: #409eff;
          margin-left: 5px;
          transition: color 0.3s;

          &:hover {
            color: #66b1ff;
            text-decoration: underline;
          }
        }
      }

      .login-button,
      .register-button {
        width: 100%;
        height: 45px;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
}

.footer-wrapper {
  margin-top: auto;

  .footer-content {
    padding: 20px 0;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    color: #606266;
    font-size: 14px;
  }
}

:deep(.el-tabs__item) {
  font-size: 1.5rem;
  font-weight: 500;
}

.el-form {
  margin-top: 1.5rem;

  .el-form-item {
    margin-bottom: 22px;
    font-size: 20px;
  }
}

.el-input {
  height: 45px;

  :deep(.el-input-group__prepend) {
    padding: 0 15px;
  }
}
</style>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { User, Lock } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import ForgetPassword from './components/forgetPassword.vue';
import { login, register } from '@/api/login';

// 图片资源
import bgLeftSrc from './images/login_left.jpg';
const bgLeftAmplify = [bgLeftSrc];

// 路由实例
const router = useRouter();

// 添加忘记密码显示状态变量 - 关键修复
const showForgetPassword = ref(false);

// 当前激活的标签页
const activeName = ref('login');
// 表单引用
const loginFormRef = ref<FormInstance>();
const registerFormRef = ref<FormInstance>();

// 修复忘记密码打开方法
const openForget = () => {
  showForgetPassword.value = true;
};

// 添加重置成功处理方法
const handleResetSuccess = () => {
  showForgetPassword.value = false;
  ElMessage.success('密码重置成功，请使用新密码登录');
};

// 加载状态
const loginLoading = ref(false);
const registerLoading = ref(false);

// 是否记住登录
const rememberLogin = ref(false);

// 登录表单数据模型
interface LoginForm {
  account: string;  // 改为string类型
  password: string;
}

const loginForm = reactive<LoginForm>({
  account: '',  // 初始化为空字符串
  password: ''
});

// 注册表单数据模型
interface RegisterForm {
  account: string;  // 改为string类型
  password: string;
  rpassword: string;
}

const registerForm = reactive<RegisterForm>({
  account: '',  // 初始化为空字符串
  password: '',
  rpassword: ''
});

// 登录表单验证规则
const loginRules = reactive<FormRules<LoginForm>>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '账号必须为数字', trigger: 'blur' },  // 新增正则验证
    { min: 6, max: 12, message: '账号长度必须为6-12位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须为6-20个字符', trigger: 'blur' }
  ]
});

// 注册表单验证规则
const registerRules = reactive<FormRules<RegisterForm>>({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '账号必须为数字', trigger: 'blur' },  // 新增正则验证
    { min: 6, max: 12, message: '账号长度必须为6-12位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^(?![0-9]+$)[a-z0-9]{1,50}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须为6-20个字符', trigger: 'blur' }
  ],
  rpassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请确认密码'));
        } else if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 切换到注册标签页
const switchToRegister = () => {
  activeName.value = 'register';
};

// 切换到登录标签页
const switchToLogin = () => {
  activeName.value = 'login';
};

// 处理登录逻辑
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    // 表单验证
    await loginFormRef.value.validate();
    loginLoading.value = true;

    // 调用登录API
    const response = await login({ ...loginForm });

    // 处理登录结果
    if (response.data?.status === 0) {
      ElMessage.success('登录成功');
      // 存储token
      if (response.data.token) {
        localStorage.setItem('token', response.data.token);
      }

      // 记住密码逻辑
      if (rememberLogin.value) {
        // 保存账号密码到localStorage
        localStorage.setItem('rememberedUser', JSON.stringify({
          account: loginForm.account,
          password: loginForm.password
        }));
      } else {
        // 清除保存的账号密码
        localStorage.removeItem('rememberedUser');
      }

      // 跳转到首页
      router.push('/home');
    } else {
      ElMessage.error(response.data?.message || '登录失败');
    }
  } catch (error: any) {
    // 错误处理
    if (error.name === 'ValidationError') {
      // 表单验证错误
      const firstError = error.errors?.[0];
      ElMessage.error(firstError?.message || '表单验证失败');
    } else if (error.response?.data?.message) {
      // API错误
      ElMessage.error(error.response.data.message);
    } else {
      // 其他错误
      ElMessage.error('登录失败，请稍后重试');
    }
  } finally {
    loginLoading.value = false;
  }
};

// 处理注册逻辑
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    // 表单验证
    await registerFormRef.value.validate();
    registerLoading.value = true;

    // 调用注册API - 彻底移除Number转换
    const response = await register({
      account: registerForm.account,
      password: registerForm.password
    });

    // 处理注册结果
    if (response.data?.status === 0) {
      ElMessage.success('注册成功');
      // 自动填充账号到登录表单
      loginForm.account = registerForm.account;
      // 切换到登录标签页
      switchToLogin();
    } else {
      ElMessage.error(response.data?.message || '注册失败');
    }
  } catch (error: any) {
    if (error.name === 'ValidationError') {
      // 表单验证错误
      const firstError = error.errors?.[0];
      ElMessage.error(firstError?.message || '表单验证失败');
    } else if (error.response?.data?.message) {
      // API错误
      ElMessage.error(error.response.data.message);
    } else {
      // 其他错误
      ElMessage.error('注册失败，请稍后重试');
    }
  } finally {
    registerLoading.value = false;
  }
};

// 页面加载时自动填充保存的账号密码
onMounted(() => {
  const savedUser = localStorage.getItem('rememberedUser');
  if (savedUser) {
    const { account, password } = JSON.parse(savedUser);
    loginForm.account = account;
    loginForm.password = password;
    rememberLogin.value = true;
  }
});

// 页脚内容
const footerItems = [
  '阿里云博客专家', '腾讯云开发者', 'CSDN认证博主', '掘金优秀作者',
  'InfoQ签约作者', 'GitHub开源贡献者', 'Stack Overflow专家'
];
</script>